﻿using System;
using System.Windows.Controls;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Windows.Media;
using System.Windows;

namespace Notes
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            #region ApplicationBar
			ApplicationBarIconButton btnAdd = (ApplicationBarIconButton)ApplicationBar.Buttons[0];
			btnAdd.Text = AppResources.strBarAdd;
            ApplicationBarIconButton btnSync = (ApplicationBarIconButton)ApplicationBar.Buttons[1];
			btnSync.Text = AppResources.strBarSync;
            #endregion

            DataContext = App.MainViewModel;
            Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        protected void MainPage_Loaded(object source, RoutedEventArgs e)
        {
            Deployment.Current.Dispatcher.BeginInvoke(delegate
            {
                App.MainViewModel.LoadData();
            });
            NavigationService.RemoveBackEntry();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            Deployment.Current.Dispatcher.BeginInvoke(delegate
            {
                App.MainViewModel.LoadData();
            });
        }

        private void MainListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (MainListBox.SelectedIndex == -1) return;
            NavigationService.Navigate(new Uri("/DetailPage.xaml?selectedIndex=" + MainListBox.SelectedIndex, UriKind.Relative));
            MainListBox.SelectedIndex = -1;
        }
		
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            base.OnBackKeyPress(e);
            if (NavigationService.CanGoBack)
                NavigationService.RemoveBackEntry();
        }

        private void ApplicationBarAdd_Click(object sender, EventArgs e)
        {
            App.ResetEditViewModel();
            NavigationService.Navigate(new Uri("/EditPage.xaml", UriKind.Relative));
        }

        private void ApplicationBarSync_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/SyncPage.xaml", UriKind.Relative));
        }

    }
}